package com.itheima.job;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import com.itheima.domain.mongo.Movement;
import com.itheima.domain.mongo.RecommendMovement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component//推荐动态定时任务类
public class RecommentMovementJob {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Scheduled(cron = "0 0 0/6 * * ?")//每6小时运行一次
    //@Scheduled(cron = "0/30 * * * * ?")
    public void RecommentMovemenUpdate(){
        System.out.println("推荐动态start");
        //从redis里查询前缀为QUANZI_PUBLISH_RECOMMEND_的key
        Set<String> keys = stringRedisTemplate.keys("QUANZI_PUBLISH_RECOMMEND_*");
        //判断非空遍历
        if (CollectionUtil.isNotEmpty(keys)) {
            for (String key : keys) {
                //替换掉前缀 得到userId
                String userId=key.replace("QUANZI_PUBLISH_RECOMMEND_","");
                //根据key查询values
                String s = stringRedisTemplate.opsForValue().get(key);
                //使用，切割获得pids
                String[] pids = s.split(",");
                //根据key删除redis里数据
                stringRedisTemplate.delete(key);
                //删除之前的推荐动态
                mongoTemplate.remove(new Query(Criteria.where("userId").is(Long.parseLong(userId))),RecommendMovement.class);
                //遍历pids
                for (String pid : pids) {
                    //调用mongo根据pid查询动态详情
                    Movement movement = mongoTemplate.findOne(new Query(Criteria.where("pid").is(Long.parseLong(pid))), Movement.class);
                    //创建推荐动态赋值
                    RecommendMovement recommendMovement=new RecommendMovement();
                    recommendMovement.setPid(Long.parseLong(pid));
                    recommendMovement.setCreated(System.currentTimeMillis());
                    recommendMovement.setPublishId(movement.getId());
                    recommendMovement.setScore(RandomUtil.randomDouble(60,100));
                    recommendMovement.setUserId(Long.parseLong(userId));
                    //使用mongo保存
                    mongoTemplate.save(recommendMovement);
                }
            }
        }
        System.out.println("推荐动态end");
    }
}
